<script setup lang="ts">
import type {
  AllTrademark,
  HasSaleAttr,
  HasSaleAttrResponseData,
  SaleAttr,
  SaleAttrResponseData, SaleAttrValue,
  SpuData,
  SpuHasImg,
  Trademark
} from "@/api/product/spu/type.ts";
import {
  reqAddOrUpdateSpu,
  reqAllSaleAttr,
  reqAllTrademark,
  reqSpuHasSaleAttr,
  reqSpuImageList
} from "@/api/product/spu";
import {computed, ref} from "vue";
import {Plus} from "@element-plus/icons-vue";
import {ElMessage, UploadProps} from "element-plus";

const emit = defineEmits(['changeScene'])
// 存已有spu的数据
const AllTrademark = ref<Array<Trademark>>([])
// spu商品图片
const imgList = ref<any>([])
// 已有spu销售属性
const saleAttr = ref<Array<SaleAttr>>([])
// 所有销售属性
const allSaleAttr = ref<Array<HasSaleAttr>>([])
// 控制对话框显示
const dialogVisible = ref<boolean>(false)
// 预览图片地址
const dialogImageUrl = ref<string>('')
// 手机还未选择的销售属性的ID与属性值的名字
let saleAttrIdAndValueName = ref<string>('')

let SpuParams = ref<SpuData>({
  category3Id:'',
  description:'',
  spuName:'',
  tmId:'',
  spuImageList:[],
  spuSaleAttrList:[]
})
const cancel = () => {
  emit('changeScene', {
    flag:0,
    params:''
  })
}

const initHasSpuData = async (spu:SpuData) => {
  SpuParams.value = spu
  // 获取全部品牌数据
  const result: AllTrademark = await reqAllTrademark()
  if(result.code === 200) {
    AllTrademark.value = result.data
    console.log("result", result)
  }
  // 获取某品牌全部售卖商品的图片
  const result1: SpuHasImg = await reqSpuImageList(spu.id as number)
  if(result1.code === 200) {
    imgList.value = result1.data.map(item => {
      return {
        name:item.imgName,
        url:item.imgUrl
      }
    })
    console.log("result1", result1)
  }
// 获取已有spu销售属性
  const result2: SaleAttrResponseData = await reqSpuHasSaleAttr(spu.id as number)
  if(result2.code === 200) {
    saleAttr.value = result2.data
    console.log("result2", result2)
  }
// 获取所有spu的销售属性
  const result3: HasSaleAttrResponseData = await reqAllSaleAttr()
  if(result3.code === 200) {
    allSaleAttr.value = result3.data
    console.log("result3", result3)
  }
}

const initAddSpu = async (C3Id:number|string) => {
  Object.assign(SpuParams.value, {
    category3Id:'',
    description:'',
    spuName:'',
    tmId:'',
    spuImageList:[],
    spuSaleAttrList:[]
  })
  imgList.value = []
  saleAttr.value = []
  saleAttrIdAndValueName.value = ''
  SpuParams.value.category3Id = C3Id
  let result: AllTrademark = await reqAllTrademark()
  let result1: HasSaleAttrResponseData = await reqAllSaleAttr()
  AllTrademark.value = result.data
  allSaleAttr.value = result1.data
}


const picturePreview: UploadProps['onPreview'] = (uploadFile: any) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

const pictureRemove = () => {

}

const beforeUpload = (uploadFile: any) => {
  if(uploadFile.type === 'image/png' || uploadFile.type === 'image/jpeg' || uploadFile.type === 'image/gif') {
    if(uploadFile.size / 1024 / 1024 < 3) {
      return true
    }else {
      ElMessage({
        type:'error',
        message:'图片大小不超过3MB'
      })
    }
  }else {
    return false
  }
}

// 未选择的销售属性
let unSelectSaleAttr = computed(()=>{
  return allSaleAttr.value.filter(item => {
    return saleAttr.value.every(item1 => {
      return item.name != item1.saleAttrName
    })
  })
})

// 添加销售属性
const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  let newSaleAttr:SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList:[]
  }
//   追加到saleAttr中
  saleAttr.value.push(newSaleAttr)
//   清空收集的数据
  saleAttrIdAndValueName.value = ''
}

// button切换到input
const toEdit = (row:SaleAttr) => {
  row.flag = true
  row.saleAttrValue = ''
}

const toLook = (row:SaleAttr) => {
  // 整理收集到的ID和属性名
  const { baseSaleAttrId, saleAttrValue } = row
  let newSaleAttrValue: SaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string
  }
  if(saleAttrValue === '') {
    ElMessage({
      type:'error',
      message:'属性值不能为空'
    })

    return
  }

  let repeat = row.spuSaleAttrValueList.find(item=>{
    return item.saleAttrValueName === saleAttrValue
  })
  if(repeat) {
    ElMessage({
      type:'error',
      message:'属性值重复'
    })
  }

  row.spuSaleAttrValueList.push(newSaleAttrValue)
  row.flag = false
}

const save = async () => {
  SpuParams.value.spuImageList = imgList.value.map((item:any)=>{
    return {
      imgName:item.name,
      imgUrl:(item.response&&item.response.data) || item.url
    }
  })

  SpuParams.value.spuSaleAttrList = saleAttr.value
  const result = await reqAddOrUpdateSpu(SpuParams.value)
  if(result.code === 200) {
    ElMessage({
      type:'success',
      message:'更新成功'
    })
  }
  emit('changeScene', {
    flag:0,
    params:SpuParams.value.id?'update':'add'
  })
}

defineExpose({
  initHasSpuData,
  initAddSpu
})
</script>

<template>
  <el-form>
    <el-form-item label="SPU名称">
      <el-input placeholder="请你输入SPU名称" v-model="SpuParams.spuName"></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="SpuParams.tmId">
        <el-option :value="item.id" :label="item.tmName" v-for="item in AllTrademark" :key="item.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input v-model="SpuParams.description" type="textarea" label="请你输入SPU描述"></el-input>
    </el-form-item>
    <el-form-item label="SPU图标">
      <el-upload v-model:file-list="imgList"
                 action="/api/admin/product/fileUpload"
                 list-type="picture-card"
                 :on-preview="picturePreview"
                 :on-remove="pictureRemove"
                 :before-upload="beforeUpload">
        <el-icon><Plus/></el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img :src="dialogImageUrl" alt="Preview Image" style="width: 100%;height: 100%;">
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select v-model="saleAttrIdAndValueName" :placeholder="unSelectSaleAttr.length ? `还未选择${unSelectSaleAttr.length}个` : '无'">
        <el-option v-for="item in unSelectSaleAttr" :key="item.id" :label="item.name" :value="`${item.id}:${item.name}`"></el-option>
      </el-select>
      <el-button :disabled="!saleAttrIdAndValueName" style="margin-left: 10px;" type="primary" @click="addSaleAttr" size="default" icon="Plus">添加属性值</el-button>
      <el-table border style="margin: 10px 0" :data="saleAttr">
        <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
        <el-table-column label="销售属性名字" width="120px" prop="saleAttrName" align="center"></el-table-column>
        <el-table-column label="销售属性值" align="center">
          <template v-slot="{row}">
            <el-tag closable @close="row.spuSaleAttrValueList.splice(index, 1)" style="margin: 0 5px" v-for="(item, index) in row.spuSaleAttrValueList" :key="item.id">
              {{item.saleAttrValueName}}
            </el-tag>
            <el-input @blur="toLook(row)" v-model="row.saleAttrValue" v-if="row.flag" placeholder="请你输入属性值" size="small" style="width: 100px"></el-input>
            <el-button v-else @click="toEdit(row)" type="primary" size="small" icon="Plus" color="#67c23a"></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template v-slot="{$index}">
            <el-button type="primary" @click="saleAttr.splice($index, 1)" size="small" icon="Delete"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button :disabled="saleAttr.length<=0" @click="save" type="primary" size="default">保存</el-button>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
    </el-form-item>
    <el-form-item></el-form-item>
  </el-form>
</template>

<style scoped lang="scss">

</style>